package com.mashang.bookkeepingbook.service.impl;

import com.mashang.bookkeepingbook.mapper.BillMapper;
import com.mashang.bookkeepingbook.pojo.*;
import com.mashang.bookkeepingbook.pojo.entity.Bill;
import com.mashang.bookkeepingbook.pojo.entity.Data;
import com.mashang.bookkeepingbook.pojo.entity.ExpensesIncome;
import com.mashang.bookkeepingbook.service.BillService;
import org.apache.ibatis.binding.BindingException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;


@Service
public class BillServiceImpl implements BillService {
    @Autowired
    private BillMapper billMapper;

    public void addBill(BillDTO billDTO) {
        Bill bill = new Bill();
        //复制
        BeanUtils.copyProperties(billDTO, bill);
        bill.setCreateTime((LocalDateTime.now()));
        billMapper.insert(bill);
    }

    /**
     * 展示列表
     * @param userId
     * @param yearMonth
     * @param categoryId
     * @return
     */
    @Override
    public List<Data> list(Integer userId, String yearMonth, Integer categoryId) {
        return billMapper.select(userId, yearMonth, categoryId);
    }

    @Override
    public ExpensesIncome billAmountCount(Integer userId, String yearMonth, Integer categoryId) {
        String year = yearMonth.substring(0,4);
        System.out.println(year);
        String month = yearMonth.substring(5,7);
        System.out.println(month);
        double expenses;
        double income;
        try {
            expenses = billMapper.selectExpenses(userId, year,month, categoryId);
        }catch(BindingException e){
            expenses=0;
        }
        try{
            income = billMapper.selectIncome(userId, year,month, categoryId);
        }catch (BindingException e){
            income=0;
        }
        return new ExpensesIncome(expenses,income);
    }

    @Override
    public Bill getById(Integer billId) {
        Bill bill=billMapper.selectById(billId);
        return bill;
    }

    @Override
    public void alterBill(AlterBillDTO alterBillDTO) {
        billMapper.update(alterBillDTO);
    }

    @Override
    public void deleteBill(Integer billId) {
        billMapper.deleteById(billId);
    }

    @Override
    public List<BillMonthlyListObject> selectAmountGroupByName(String type, Integer userId, String year, String month) {
        return billMapper.selectAmountGroupByName(type,userId,year,month);
    }
}
